# handler_xmpp.py
#
#

""" xmpp request handler. """


# set start time
import time

starttime = time.time()

# gozerlib imports

from gozerlib.xmpp.bot import XMPPBot
from gozerlib.xmpp.event import XMPPEvent
from gozerlib.utils.generic import fromenc, toenc, getversion
from gozerlib.utils.lazydict import LazyDict
from gozerlib.aliases import aliasget
from gozerlib.utils.exception import handle_exception
from gozerlib.plugins import plugs
from gozerlib.utils.auth import checkuser
from gozerlib.config import Config
from gozerlib.boot import boot

# google imports

from google.appengine.api import xmpp
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.api import users as gusers
from google.appengine.ext import db
from google.appengine.ext.webapp import xmpp_handlers

from waveapi.simplejson import loads

import wsgiref.handlers
import sys
import time
import types
import logging

logging.warn(getversion('XMPP'))

boot()
bot = XMPPBot('cmndxmpp')
plugs.loadall()

config = Config('mainconfig')

def xmppbox(response):
    response.out.write("""
          <form action="/_ah/xmpp/message/chat/" method="post">
            <div><b>enter command:</b> <input type="commit" name="body">
          </form>
          """)

class XMPPHandler(webapp.RequestHandler):

    """ relay incoming messages to the bot. """

    def get(self):
        xmppbox(self.response)

    def post(self):
        logging.debug("XMPP incoming: %s" % self.request.remote_addr)          

        if config.debug:
            self.request.POST['from'] = 'test@bla'
            self.request.POST['to'] = 'test@bla'

        if not self.request.POST.has_key('from'):
            logging.debug('no from in POST: %s' % str(self.request.POST))
            return

        if not self.request.POST.has_key('to'):
            logging.debug('no to in POST: %s' % str(self.request.POST))
            return

        if not self.request.POST.has_key('body'):
            logging.debug('no body in POST: %s' % str(self.request.POST))
            return

        event = XMPPEvent().parse(self.request, self.response)

        if not event.txt:
            event.txt = 'help'

        event.bot = bot
        event.bot.doevent(event)

application = webapp.WSGIApplication([('/_ah/xmpp/message/chat/', XMPPHandler),
                                      ('/_ah/xmpp/message/chat', XMPPHandler)],
                                      debug=True)

def main():
    global bot
    global application
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
